package com.yuzhitong.shapi.activity;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.flyco.tablayout.SlidingTabLayout;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.base.BaseLayoutActivity;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.fragment.SearchCategoryFragment;
import com.yuzhitong.shapi.fragment.SearchMovieFragment;
import com.yuzhitong.shapi.fragment.SearchWebFragment;
import com.yuzhitong.shapi.util.StringUtil;
import com.yuzhitong.shapi.util.UiUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Brsya
 * CreateDate: 2022/5/9  15:21
 * Description:
 * 影视搜索
 */
public class MovieSearchActivity extends BaseLayoutActivity implements View.OnClickListener {


    private RelativeLayout rlSearchInputBox;
    private EditText etSearch;
    private LinearLayout llSearchIcon;
    private LinearLayout llSearchClear;
    private LinearLayout llTopTitle;
    private TextView tvTitleBack;
    private LinearLayout llSearchResult;
    private SlidingTabLayout tlMovieSearchTitle;
    private ViewPager vpMovieSearchResultBox;
    private int heightPixels;
    private boolean imIsShow;

    private String[] tabs = {"影视", "直搜", "必应", "神马", "百度", "头条"};
    private List<Fragment> fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_search);
        setDarkStatus();
        initView();
        initListener();
    }

    private void initView() {
        llTopTitle = findViewById(R.id.ll_top_title);
        rlSearchInputBox = findViewById(R.id.rl_search_input_box);
        etSearch = findViewById(R.id.et_search);
        llSearchIcon = findViewById(R.id.ll_search_icon);
        llSearchClear = findViewById(R.id.ll_search_clear);
        tvTitleBack = findViewById(R.id.tv_title_back);
        llSearchResult = findViewById(R.id.ll_search_result);
        tlMovieSearchTitle = findViewById(R.id.tl_movie_search_title);
        vpMovieSearchResultBox = findViewById(R.id.vp_movie_search_result_box);

        UiUtil.setStatusPadding(this, llTopTitle);
    }

    private void initListener() {

        llSearchClear.setOnClickListener(this);
        tvTitleBack.setOnClickListener(this);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                llSearchClear.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
            }
        });
        // 获取屏幕宽度
        WindowManager manager = getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        heightPixels = outMetrics.heightPixels;

        // 关闭输入法自动失去焦点
        etSearch.getViewTreeObserver().addOnGlobalLayoutListener(() -> {

            //获取当前根视图在屏幕上显示的大小
            Rect r = new Rect();
            etSearch.getWindowVisibleDisplayFrame(r);

            // 判断是否显示键盘
            if (heightPixels - r.bottom > 300) {
                imIsShow = true;
            }
            // 判断显示高度是否等于屏幕高度  键盘显示转为隐藏
            if (heightPixels == r.bottom && imIsShow) {
                imIsShow = false;
                etSearch.clearFocus();
            }
        });
        etSearch.requestFocus();
        //        new Handler(getMainLooper())
        //                .postDelayed(new Runnable() {
        //                    @Override
        //                    public void run() {
        //                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //                        imm.showSoftInput(etSearch, InputMethodManager.RESULT_SHOWN);
        //                        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
        //                    }
        //                }, 300);


        etSearch.setOnEditorActionListener((textView, i, keyEvent) -> {
            // 搜索或回车
            if (i == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getAction() == KeyEvent.KEYCODE_ENTER)) {
                String search = etSearch.getText().toString();
                handleSearchTet(search);
                return true;
            }
            return false;
        });

        fragments = new ArrayList<>();
        fragments.add(SearchCategoryFragment.newInstance(null));
        fragments.add(SearchMovieFragment.newInstance(null));
        fragments.add(SearchWebFragment.newInstance(Contents.POSITION_MOVIE_BING));
        fragments.add(SearchWebFragment.newInstance(Contents.POSITION_MOVIE_SHM));
        fragments.add(SearchWebFragment.newInstance(Contents.POSITION_MOVIE_BD));
        fragments.add(SearchWebFragment.newInstance(Contents.POSITION_MOVIE_TT));

        vpMovieSearchResultBox.setOffscreenPageLimit(5);
        vpMovieSearchResultBox.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return tabs.length;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return tabs[position];
            }
        });

        tlMovieSearchTitle.setViewPager(vpMovieSearchResultBox);

    }

    private void handleSearchTet(String search) {
        if (StringUtil.isEmpty(search)) {
            return;
        }
        for (Fragment fragment : fragments) {
            if (fragment instanceof SearchCategoryFragment) {
                ((SearchCategoryFragment) fragment).setSearchName(search);
            } else if (fragment instanceof SearchMovieFragment) {
                ((SearchMovieFragment) fragment).setSearchName(search);
            } else if (fragment instanceof SearchWebFragment) {
                ((SearchWebFragment) fragment).setSearchName(search);
            }
        }
        etSearch.clearFocus();
        InputMethodManager imm =
                (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_search_clear) {
            etSearch.setText("");
        } else if (id == R.id.tv_title_back) {
            finish();
        }

    }
}
